﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using Mall.Core;
using Mall.Data;
using Solution;
using Solution.Provide.Mvc;

namespace Mall.AdminSystem.Controllers
{
    /// <summary>
    /// 后台系统基类
    /// </summary>
    public class BaseController : BaseWebController
    {

        #region 属性
        /// <summary>
        /// 访问URL 带有域名
        /// </summary>
        public string HostUrl { get; set; }

        /// <summary>
        /// 访问的URL， 不带域名
        /// </summary>
        public string RawUrl { get; set; }
        /// <summary>
        /// 上一次访问URL(来源地址)
        /// </summary>
        public string ReferrerUrl { get; set; }

        /// <summary>
        /// 请求的IP
        /// </summary>
        public string IP { get; set; }
        #endregion
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            Init(requestContext);
        }


        /// <summary>
        /// 初始化一些元数据
        /// </summary>
        /// <param name="requestContext"></param>
        private void Init(RequestContext requestContext)
        {
            //RoleMenuCore rmCore = new RoleMenuCore();
            MenuActionCore maCore = new MenuActionCore();
            AdminCore adCore = new AdminCore();

            if (requestContext.HttpContext.Request.Url != null) this.HostUrl = requestContext.HttpContext.Request.Url.ToString();
            this.ReferrerUrl = requestContext.HttpContext.Request.UrlReferrer?.ToString() ?? string.Empty;
            this.IP = requestContext.HttpContext.Request.UserHostAddress;
            this.RawUrl = requestContext.HttpContext.Request.RawUrl;

            ViewBag.RawUrl = RawUrl;//string.Format("/{0}/{1}", requestContext.RouteData.Values["controller"], requestContext.RouteData.Values["action"]); 


            string burl = ConfigurationManager.AppSettings["ImgSiteUrl"];
            if (string.IsNullOrEmpty(burl))
            {
                burl = "/cache/";
            }
            ViewBag.StaticSiteUrl = burl;

            ViewBag.SiteName = "邻信App2.0后台管理系统";

            ViewBag.UserName = (SessionHelper.GetSession("loginUser") as Sys_Admin).A_Name;

            #region 根据权限加载菜单
            string idstring = FormTicketHelper.GetUserId();
            if (string.IsNullOrEmpty(idstring))
            {
                return;
            }
            Guid uid = Guid.Parse(idstring);

            var firstOrDefault = adCore.LoadEntity(o => o.A_Id == uid && o.A_Status == 0);
            var isSuperAdmin = firstOrDefault != null && firstOrDefault
                .Sys_AdminRole.Any(o => "*".Equals(o.Sys_Role.R_Permission));  //是否拥有最大权限

            IEnumerable<Sys_MenuAction> menuList = SessionHelper.GetSession("GLOBAL_ROLE_MENU" + uid) as IEnumerable<Sys_MenuAction>;

            if (menuList == null)
            {
                menuList = adCore.BuildMenu(uid, isSuperAdmin);
                SessionHelper.SetSession("GLOBAL_ROLE_MENU" + uid, menuList);  //当前登录用户的权限菜单
            }
            ViewBag.MenuAction = menuList.Where(o => o.A_Flag == 1);//角色权限拥有的菜单权限（不包含功能权限）

            if (CacheHelper.GetCache("GLOBAL_MENU_ACTION") == null)
            {
                var ma = maCore.LoadEntities(o => o.A_State == 0).ToList();
                CacheHelper.SetCache("GLOBAL_MENU_ACTION", ma);  //所有的权限菜单
            }
            //if (CacheHelper.GetCache("GLOBAL_ROLE_MENU") == null)
            //{
            //    var rm = rmCore.LoadEntities().ToList();
            //    CacheHelper.SetCache("GLOBAL_ROLE_MENU", rm);  
            //}
            if (SessionHelper.GetSession("SESSION_SUPER_PERMISSION") == null)
            {
                SessionHelper.SetSession("SESSION_SUPER_PERMISSION", isSuperAdmin ? "1" : "0");
            }

            #endregion
        }
    }
}
